import { UploadOutlined } from '@ant-design/icons';
import {
  ProForm,
  ProFormDependency,
  ProFormSelect,
  ProFormText,

} from '@ant-design/pro-components';
import { useModel, useRequest } from '@umijs/max';
import { Button, message, Upload } from 'antd';
import React from 'react';

import useStyles from './index.style';
import { fetchDeptvaluelable, fetchSectionvaluelable, fetchGroupvaluelable } from '../../../../utility/fetchorganizationforselect';
import { flushSync } from 'react-dom';
import { modifyBaseSetting, avarterUpload } from '@/services/ant-design-pro/api';
import type { GetProp, UploadProps } from 'antd';
// import reqwest from 'reqwest';

type FileType = Parameters<GetProp<UploadProps, 'beforeUpload'>>[0];

const beforeUpload = (file: FileType) => {
  const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/png';
  if (!isJpgOrPng) {
    message.error('只能上传jpeg和png文件格式!');
  }
  const isLt2M = file.size / 1024 / 1024 < 2;
  if (!isLt2M) {
    message.error('上传图片只能小于2MB!');
  }
  return isJpgOrPng && isLt2M;
};

const BaseView: React.FC = () => {

  const { run: modifybase } = useRequest(modifyBaseSetting, {
    manual: true,
    onSuccess: () => {
      message.success('更新基本信息成功');
    },
    onError: () => {
      message.error('更新基本信息失败!');
    },
  });

  const { initialState, setInitialState } = useModel('@@initialState');
  const { currentUserInfo } = initialState || {};
  const { styles } = useStyles();

  // 上传头像
  const Avatarprops = {
    name: "avatar",
    showUploadList: false,//设置只上传一张图片，根据实际情况修改
    customRequest: async (info: any) => {//手动上传
      const result = await avarterUpload(info.file, currentUserInfo?.loginname ?? '');
      // console.log(newavater);
      if (result.status === 200) {
        flushSync(() => {
          setInitialState((s) => ({
            ...s,
            currentUserInfo: {
              ...s?.currentUserInfo,
              avatar: info.file.name,
            },
          }));
        });
        message.success(result.data);
      }
      else {
        message.error(result.data);
      }
    },
  }
  // 头像组件 方便以后独立，增加裁剪之类的功能
  //该组件接受一个 avatar 对象，该对象必须包含一个 avatar 字符串属性
  //showUploadList={false} 表示不显示上传列表
  //图像的加载不会受到同源策略的限制
  const AvatarView = ({ avatar }: { avatar: string }) => (
    <>
      <div className={styles.avatar_title}>头像</div>
      <div className={styles.avatar}>
        <img src={avatar} alt="avatar" />
      </div>

      <Upload
        // showUploadList={false}
        beforeUpload={beforeUpload}
        {...Avatarprops}
      >
        <div className={styles.button_view}>
          <Button>
            <UploadOutlined />
            更换头像
          </Button>
        </div>
      </Upload>
    </>
  );

  //更新信息
  const handleFinish = async (value: any) => {

    value.loginname = currentUserInfo?.loginname;
    flushSync(() => {
      setInitialState((s) => ({
        ...s,
        currentUserInfo: {
          ...s?.currentUserInfo,
          realname: value.realname,
          dept: value.dept,
          section: value.section,
          group: value.group,
          mobilephone: value.mobilephone,
          email: value.email,
        },
      }));
    });
    //后端执行更新信息
    await modifybase(value);
    
  };
  return (
    <div className={styles.baseView}>

      <>
        <div className={styles.left}>
          <ProForm
            layout="vertical"
            onFinish={handleFinish}
            submitter={{
              searchConfig: {
                submitText: '更新基本信息',
              },
              render: (_, dom) => dom[1],
            }}
            initialValues={{
              ...currentUserInfo,

            }}
          // hideRequiredMark
          >
            <ProFormText
              width="md"
              name="email"
              label="邮箱"
              rules={[
                {
                  required: true,
                  message: '请输入您的邮箱!',
                },
              ]}
            />
            <ProFormText
              width="md"
              name="realname"
              label="姓名"
              rules={[
                {
                  required: true,
                  message: '请输入您的姓名!',
                },
              ]}
            />

            <ProForm.Group title="组织机构" size={8}>
              <ProFormSelect
                rules={[
                  {
                    required: true,
                    message: '请输入部门!',
                  },
                ]}
                width="sm"
                // fieldProps={{
                //   labelInValue: true,
                // }}
                name="dept"
                className={styles.phone_number}
                request={async () => {
                  // 可以根据需要的逻辑来选择 categoryClass  
                  return fetchDeptvaluelable();
                }}
              />
              <ProFormDependency name={['dept']}>
                {({ dept }) => {
                  return (
                    <ProFormSelect
                      params={{
                        key: dept,
                      }}
                      name="section"
                      width="sm"
                      rules={[
                        {
                          required: true,
                          message: '请输入科室!',
                        },
                      ]}
                      disabled={!dept}
                      className={styles.phone_number}
                      request={async () => {
                        if (!dept) {
                          return [];
                        }
                        return fetchSectionvaluelable(dept);
                      }}
                    />
                  );
                }}
              </ProFormDependency>
              <ProFormDependency name={['dept', 'section']}>
                {({ dept, section }) => {

                  return (
                    <ProFormSelect
                      params={{
                        deptKey: dept,
                        sectionKey: section,
                      }}
                      name="group"
                      width="sm"
                      rules={[
                        {
                          required: true,
                          message: '请输入小组!',
                        },
                      ]}
                      disabled={!dept || !section}
                      className={styles.phone_number}
                      request={async () => {
                        if (!dept || !section) {
                          return [];
                        }
                        return fetchGroupvaluelable(dept, section);
                      }}
                    />
                  );
                }}
              </ProFormDependency>
            </ProForm.Group>


            <ProFormText
              name="mobilephone"
              label="联系电话"
              rules={[
                {
                  required: true,
                  message: '请输入您的联系电话!',
                },
                {
                  pattern: /^1[3-9]\d{9}$/, // 正则表达式, 验证手机号格式（以1开头，11位数字）  
                  message: '请输入有效的手机号!', // 自定义错误信息  
                },
              ]}
            >

            </ProFormText>
          </ProForm>
        </div>
        <div className={styles.right}>
          
          <AvatarView avatar={window.avatarpath + currentUserInfo?.avatar} />
        </div>
      </>

    </div>
  );
};
export default BaseView;
